import torndb
from Judge import judge
from Config import *
from Update import update

def update_result(result, runid):
    try:
        db = torndb.Connection(db_host, db_name, user = db_user, password= db_password)
    except:
        pass
    if result["runtime"] == None:
        result["runtime"] = "0"
    if result["runmem"] == None:
        result["runmem"] = "0"
    db.execute("update status set statu='%s',remark=1,runtime='%s',runmem='%s' where runid=%s" % (str(result["statu"]), str(result["runtime"]), str(result["runmem"]), str(runid)))

def worker(workerId):
    while True:
        task = q.get()
        print("get a task")
        runid = task.runid
        pid = task.pid
        cid = task.cid
        code = task.code
        author = task.author
        language = task.language

        result = judge(runid, pid, cid, code, author, language)

        if result == False:
            continue 

        dblock.acquire()
        update_result(result, runid)
        print("worker "+str(workerId)+" grade runid "+str(runid))
        dblock.release()

        q.task_done()
        update()
